package com.example.graduation.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.graduation.entity.Goods;
import com.example.graduation.entity.Hot;
import com.example.graduation.mapper.HotMapper;
import com.example.graduation.service.HotService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author xyc
 * @since 2022-02-11
 */
@Service
public class HotServiceImpl extends ServiceImpl<HotMapper, Hot> implements HotService {

    @Resource
    private HotMapper hotMapper;


    /**
     * 更新或者插入新的热搜数据
     *
     * @param goodsId
     * @author xieyucan
     * CreateDate 2022/3/23 10:58
     */
    @Override
    public void updateHot(Integer goodsId, String goodsName) {
        try {
            QueryWrapper<Hot> wrapper = new QueryWrapper<>();
            wrapper.eq("goods_id", goodsId);
            Hot one = hotMapper.selectOne(wrapper);
            if (one == null) {
                Hot hot = new Hot();
                hot.setCount(1);
                hot.setGoodsId(goodsId);
                hot.setGoodsName(goodsName);
                hotMapper.insert(hot);
            } else {
                UpdateWrapper<Hot> hotUpdateWrapper = new UpdateWrapper<>();
                hotUpdateWrapper.eq("goods_id", goodsId);
                Integer count = one.getCount();
                Integer add = count + 1;
                one.setCount(add);
                hotMapper.update(one, hotUpdateWrapper);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("操作失败");
        }
    }


    /**
     * 利用分页查询出热搜的前八条热搜数据
     *
     * @return {@link Page< Hot>}
     * @author xieyucan
     * CreateDate 2022/3/23 11:04
     */
    @Override
    public Page<Hot> searchHotList() {
        try {
            QueryWrapper<Hot> wrapper = new QueryWrapper<>();
            wrapper.orderByDesc("count");
            Page<Hot> hotPage = hotMapper.selectPage(new Page<>(1, 8), wrapper);
            return hotPage;
        } catch (Exception e) {
            throw new RuntimeException("查询失败");
        }
    }
}
